import Gmap from '@/utils/HshMap/Gmap.jsx';
import { ScaleLine } from 'ol/control';
import React from 'react';
import { connect } from 'dva';
import { Layout, Modal, Button, Icon, Card, InputNumber, Input, Divider, Select,  Tabs } from 'antd';
const { TabPane } = Tabs;
import Goverlay from "@/utils/HshMap/Goverlay";
import Ginteraction from "@/utils/HshMap/Ginteraction";
import Glayers from "@/utils/HshMap/Glayers";
const {  Content, Sider } = Layout;
import styles from './index.less'
import './index.module.css'
import GexportPDF from "@/utils/HshMap/GexportPDF";
import compass from "@/assets/map/compass.svg";
import Gstyle from "@/utils/HshMap/Gstyle";

// 业务组件
import GraphicsElement from "./GraphicsElement";
import GraphicsLayer from "./GraphicsLayer";
import PublicInterface from "@/utils/Common/PublicInterface";

import { Spin, Switch, Alert } from 'antd';

import 'ol-ext/control/Legend.css';
import Legend from 'ol-ext/control/Legend';

import html2canvas from 'html2canvas';

const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 10 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 },
  },
};

@connect(({ graphics }) => ({ graphics }))
class GraphicsOutPut extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      height: 768,
      gmap: null,
      tabKey: 'yuansu',
      checkLayerList: [],
      layerList: [],
      visible: false,
      confirmLoading: false,
      formatValue: 'a4',
      resolutionValue: 60,
      loading: false,
      titleMap: '',
      tableColsList: {},
      modalLoading: false,
      imageUrl: '',
      legend: null
    }

    this.selectOverlay = null;
    this.featureSelected = null;
    this.mapDivId = `map-1`;
    this.map = new Gmap().map;
    //添加比例尺控件
    this.map.addControl(new ScaleLine());
    //自定义指南针控件
    // this.map.addControl(new Gcompass.RotateNorthControl());

    //添加图例
    this.state.legend = new Legend({
      title: '图例',
      style: '',
      collapsed: false,
      collapsible: true,
      // margin: 10,
      size: [24, 24]
    });
    this.map.addControl(this.state.legend);
  }

  onChange = e => {
    console.log('checked = ', e.target ? e.target.value : '');
  };

  componentDidMount() {
    this.init();
    this.map.setTarget(this.mapDivId);
    this.ginteraction = new Ginteraction(this.map);
    this.ginteraction.on_pointermove(this.select_hover_callback);
    this.setState({
      gmap: this.map,
    });
    var img = document.createElement('img');
    img.src = compass;
    var olCompass = document.getElementsByClassName('ol-compass')[0];
    if (olCompass) {
      olCompass.innerHTML = '';
      olCompass.appendChild(img);
    }
    // 指北针提示汉化
    document.getElementsByClassName('ol-rotate-reset')[0].title='指北针';
    //强制重新计算地图视口大小
    var self = this;
    setTimeout(function () {
      self.map.updateSize();
    }, 100);

    //隐藏图例
    document.getElementsByClassName('ol-legend')[0].style.display = 'none';
    // 窗口resize 监听
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  }

  // 取父div的height
  handleResize = () =>{
    const self = this;
    const divWidth = document.body.clientWidth;
    const divHeight = document.body.clientHeight;
    self.setState({ width: divWidth, height: divHeight - 66 });
    setTimeout(function () {
      self.map.updateSize();
    }, 100);
  };

  init = () => {
    this.queryServer();
    var self =this;
    new PublicInterface().pubtabcolsList(this.props,{ifanalysis: 1},function (data) {
      self.setState({
        tableColsList: data
      })
    });
  }
  // ajax请求
  queryServer = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'graphics/spaceResourcesQuery',
      payload: {},
    });
  }

  //新增legend
  legendAddRow = (layerType,tableId,mapType,mapName,description) => {
    var style = null,typeGeom = null;
    var classify = layerType.substr(layerType.lastIndexOf('/')+1);
    if(mapType=='layer_point'){
      // if (layerType.indexOf('poi')!=-1){
      //   style = Gstyle.styleDefault();
      // }else {
        style = Gstyle.styleCacheIndexPoint(description, classify);
      // }
      typeGeom = "Point" ;
    }else if(mapType=='layer_polygon'){
      style = Gstyle.styleCacheIndexPolygon(description,classify);
      typeGeom = "Polygon" ;
    }else if(mapType=='layer_line'){
      style = Gstyle.styleCacheIndexLineString(description,classify);
      typeGeom = "LineString" ;
    }

    this.state.legend.addRow({
      title: mapName,
      typeGeom: typeGeom,
      style: style
    });
    this.state.legend.refresh();
  }
  //legend是否删除
  legendVisible = (layerType,tableId,mapType,mapName) =>{
    this.state.legend.refresh();
    var legendLength = this.state.legend.getLength();
    if (legendLength > 0) {
      for (let j = 0; j < legendLength; j++) {
        if (this.state.legend.getRow(j)["title"] == mapName){
          this.state.legend.removeRow(j);
          return;
        }
      }
    }
  }

  handleLayerChange = (e) => {
    let { checkLayerList, layerList } = this.state;
    console.log(e.target,'===')
    console.log(layerList,'---')
    if (e.target.checked == true) {
      for (let i = 0; i < layerList.length; i++) {
        if (layerList[i].layerType != null && layerList[i].layerType.indexOf(e.target.value) != -1) {

          layerList[i].layerVector.setVisible(true);
          this.legendAddRow(e.target.value,e.target.appMapId,e.target.mapType,e.target.mapName,e.target.description);
          return false;
        }
      }
      checkLayerList.push(e.target.value);

      this.setState({
        checkLayerList
      }, () => {
        this.addMapLayer(e.target.value,e.target.tableId,e.target.mapType,e.target.mapName,e.target.description);
      })
    } else {
      checkLayerList.forEach(function (item, index, arr) {
        if (item == e.target.value) {
          arr.splice(index, 1);
        }
      });

      this.setState({
        checkLayerList
      })

      for (let i = 0; i < layerList.length; i++) {
        if (layerList[i].layerType != null && layerList[i].layerType.indexOf(e.target.value) != -1) {
          layerList[i].layerVector.setVisible(false);
          break;
        }
      }
      this.legendVisible(e.target.value,e.target.appMapId,e.target.mapType,e.target.mapName);
    }
  }

  // 加载图层
  addMapLayer = (layerType,tableId,mapType,mapName,description) => {
    const { dispatch } = this.props;
    var vector = new Glayers().addVectorLayer('space/arcgisFeatureServerQuery',dispatch,' status_cd=1 ',layerType,4326,description);
    vector.set('id', tableId);
    this.map.addLayer(vector);
    let { layerList } = this.state;
    layerList.push({'layerType': layerType, 'layerVector': vector});

    this.legendAddRow(layerType,tableId,mapType,mapName,description);
  };

  //hover要素
  select_hover_callback = (e) => {
    if (e.dragging) {
      return;
    }
    var self = this;
    var pupupProperties ={};
    self.clearStyle();
    self.map.forEachFeatureAtPixel(e.pixel, function (f, layer) {
      self.clearStyle();
      self.featureSelected = f;
      f.setStyle(Gstyle.pointermove_style);
      let coodinate = e.coordinate;
      let properties = f.getProperties();
      if(layer!=null && layer.values_.id!=null) {
        if(self.state.tableColsList[layer.values_.id]!=null && self.state.tableColsList[layer.values_.id].length > 0){
          self.state.tableColsList[layer.values_.id].forEach(item => {
            if(item.columnType == "timestamp"){
              pupupProperties[item.description] = properties[item.columnName] ? new Date(properties[item.columnName]).toLocaleDateString() : '--';
            }else {
              pupupProperties[item.description] = properties[item.columnName] ? properties[item.columnName] : '--';
            }
          });
          var overlay = Goverlay.getOverlay_default('hover', coodinate, 1, pupupProperties);
          self.selectOverlay = overlay;
          self.map.addOverlay(overlay);
        }
      }
    });

  }

  clearStyle = () => {
    var self = this;
    if (self.selectOverlay) {
      self.selectOverlay.setPosition(undefined);
      self.selectOverlay = null;
    }
    if (self.featureSelected) {
      self.featureSelected.setStyle(null);
      self.featureSelected = null;
    }
  }


  showModal = () => {
    this.setState({
      visible: true,
      loading: true,
      titleMap: document.getElementById('titleId').value,
    });
    var _this = this;
    html2canvas(document.getElementsByClassName('ol-viewport')[0],{
      scale:2,
      logging:false,
      useCORS:true,
      allowTaint:true,
      ignoreElements:(element)=>{
          if(element.id==='printHide')
          return true;
      },
    }).then(function(canvas) {
        var data = canvas.toDataURL('image/jpeg');
        _this.setState({
          coverUrl: data
        });
    });
  };

  handleOk = () => {
    let { formatValue, resolutionValue, titleMap } = this.state;
    this.setState({
      confirmLoading: true,
      modalLoading: true
    });
    new GexportPDF().exportPDFFunction(this.map, formatValue, resolutionValue, titleMap, this.handleCancel);
  };

  handleCancel = () => {
    console.log('Clicked cancel button');
    this.setState({
      visible: false,
      confirmLoading: false,
      modalLoading: false
    });
  };

  handleChange = (value) => {
    console.log('selected', value);
    this.state.formatValue = value;
  }

  inputChange = (value) => {
    console.log('changed', value);
    this.state.resolutionValue = value;
  }

  render() {
    const { SpaceResource } = this.props.graphics;

    const { visible, confirmLoading, checkLayerList } = this.state;
    return (
      <Layout style={{ padding: '0' }}>
        <Sider width={236} style={{ background: '#fff', padding: '0', border: '1px solid rgb(232, 232, 232)', height: 'calc(100vh - 110px)' }}>
          <div style={{ background: '#EBF5EF',height: '40px',lineHeight: '40px',paddingLeft: '20px' }}>
            <span style={{ fontSize: '12px',color:'#40AF59' }}>制图输出</span>
          </div>
          {/* 面板切换 start */}
          <Tabs>
            <TabPane tab="元素" key="1" style={{padding: '20px'}}>
              <GraphicsElement />
            </TabPane>
            <TabPane tab="图层" key="2" style={{paddingLeft: '20px',height: this.state.height-80 }}>
              <GraphicsLayer
                defaultValue={checkLayerList} // 父传子
                onLayerChange={this.handleLayerChange} // 子传父
              />
            </TabPane>
          </Tabs>
          {/* 面板切换 end */}
        </Sider>
        <Layout style={{ padding: '0' }}>
          <Content
            style={{
              background: '#f2f2f2',
              padding: 0,
              margin: 0,
              minHeight: 280,
            }}
          >
            <Card title="" style={{ textAlign: "right", background: '#f2f2f2', border: 0 }} id="cardDIv">
              <div title="" style={{ textAlign: "center", background: '#fff', padding: '10px' }}>
                <span className={styles.showInput} id="showInput">
                  <Input id="titleId" placeholder="请输入标题" style={{ margin: '10px 0px', width: 300, height: 30, textAlign: 'center', border: '1px solid #9F9F9F', color: '#9F9F9F' }} />
                </span>
                <span>
                  <Button type="primary" id="export-pdf" style={{ position: 'absolute', top: '18px', right: '48px' }} onClick={this.showModal}>
                    输出图片
                  </Button>
                </span>
                <div id={this.mapDivId} className="map"></div>
              </div>
            </Card>


            <Modal
              title="输出设置"
              visible={visible}
              onOk={this.handleOk}
              okText="预览并下载"
              confirmLoading={confirmLoading}
              onCancel={this.handleCancel}
            >
            <Spin spinning={this.state.modalLoading}>
              <div>
                <div className={styles.row}>
                  <div className={styles.itemLabel}>输出尺寸：</div>
                  <div className={styles.itemValue}>
                    <Select id="format" defaultValue="a4" disabled={confirmLoading} style={{ width: 120 }} onChange={this.handleChange}>
                      {/*<Option value="a1">A1</Option>*/}
                      {/*<Option value="a2">A2</Option>*/}
                      {/*<Option value="a3">A3</Option>*/}
                      <Option value="a4">A4</Option>
                      <Option value="a5">A5</Option>
                    </Select>
                  </div>
                </div>
                <div className={styles.row}>
                  <div className={styles.itemLabel}>分辨率：</div>
                  <div className={styles.itemValue}><InputNumber id="resolution" disabled={confirmLoading} min={60} max={180} defaultValue={60}
                    onChange={this.inputChange} /> dpi
                    </div>
                </div>
                <div className={styles.row}>
                  <div className={styles.itemLabel}>预览：</div>
                  <div className={styles.itemValue}>
                    <Card
                      className={styles.previewCard}
                      title={this.state.titleMap}
                      hoverable
                      // loading={true}
                      style={{ width: 320, textAlign: "center" }}
                      cover={<img alt="" id="cardImg" src={this.state.coverUrl} />}
                    >
                    </Card>
                  </div>
                </div>
              </div>
              </Spin>
            </Modal>

          </Content>
        </Layout>
      </Layout>
    );
  }
}

export default GraphicsOutPut;
